<template>
  <div class="chart-line-alert-root" ref="ChartLineAlertRef" v-loading="rqLoading"
    element-loading-text="正在聚合警告信息, 请稍后..."></div>
</template>

<script setup lang="ts">
import { ref, onMounted, inject, nextTick } from "vue";
import { alertLineApi } from "@/api/alert";
// echart
import * as echartTheme from '@/assets/styles/xz/echartTheme';
import * as echarts from 'echarts/core';
import { GridComponent, TooltipComponent } from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([GridComponent, TooltipComponent, LineChart, UniversalTransition, CanvasRenderer]);

// -------------------- inject
const currentMachine: any = inject('currentMachine')

// -------------------- data

const rqLoading = ref<boolean>(true);
const ChartLineAlertRef = ref<any>(null);
let chartLineAlert: any;
let chartData = {
  x: [],
  data: []
}

const getAlertLine = () => {
  rqLoading.value = true;
  let param = {
    appName: currentMachine.value.appName
  }
  alertLineApi(param).then(resp => {
    chartData.x = resp.data.dates;
    chartData.data = resp.data.counts;
    renderChart(() => {
      setTimeout(() => {
        rqLoading.value = false;
      }, 300);
    });
  });
}

const renderChart = (callback?: any) => {
  chartLineAlert.setOption({
    title: {
      text: '48小时警告统计(每1小时聚合)',
      right: 0,
      textStyle: echartTheme.title().textStyle
    },
    tooltip: echartTheme.tooltip(),
    grid: { left: 10, right: 20, bottom: 10, top: 30, containLabel: true },
    xAxis: { type: 'category', data: chartData.x.map((item: any) => item.substring(5).replaceAll(' ', '\n')) },
    yAxis: { splitLine: { lineStyle: { color: [echartTheme.common().axisLineColor] } } },
    series: [
      {
        type: 'line',
        name: '警告数',
        smooth: true, // 平滑曲线
        showSymbol: false,
        sampling: 'lttb',
        data: chartData.data,
        lineStyle: { width: 2, color: '#BE9500' },
        itemStyle: { color: '#9A7900' },
        areaStyle: {
          color: {
            type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [{ offset: 0, color: '#FFC800' }, { offset: 1, color: '#FFC80000' }]
          }
        }
      }
    ]
  });
  if (callback !== undefined) {
    callback();
  }
}

const reload = () => {
  nextTick(() => {
    getAlertLine();
  })
}

const windowResize = () => {
  chartLineAlert.resize();
}

onMounted(() => {
  chartLineAlert = echarts.init(ChartLineAlertRef.value);
  windowResize();
})

defineExpose({
  reload, windowResize
})
</script>

<style scoped lang="scss">
.chart-line-alert-root {
  @include box(100%, 100%);
}
</style>